package com.back.network.netty.handlers;

import javax.annotation.Resource;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.back.network.netty.metrics.handler.BytesMetricsHandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.stream.ChunkedWriteHandler;

@Component
public class ChildUserChannel extends ChannelInitializer<SocketChannel> {

	@Resource
	private BytesMetricsHandler bytesMetricsHandler;
	/**
	 * 初始行的最大长度(例如“GET / HTTP / 1.0”),默认4096
	 * </p>
	 * IE 2083
	 * </p>
	 * firefox 65535
	 * </p>
	 * chrome 8182
	 * </p>
	 * Safari 80000
	 * </p>
	 * Opera 190000
	 **/
	private final static int MAX_INITIAL_LINE_LENGTH = 20 * 1024;
	/** 最大请求头,默认8192 **/
	private final static int MAX_HEADER_SIZE = 40 * 1024;
	/** 最大内容块,默认8192,平均值在60*1024 **/
	private final static int MAX_CHUNK_SIZE = 100 * 1024;
	/** 最大内容块,默认8192,平均值在60*1024 **/
	private final static int MAX_CONTENT_LENGTH = 10 * 1024 * 1024;

	/**
	 * 由于UserChannelHandler存在局部变量messages,并发时会出现数据错乱问题。因此需要多实例。 @Scope("prototype")
	 * + ObjectFactory 来产生多实例效果
	 */
	@Autowired
	private ObjectFactory<UserChannelHandler> objectFactory;

	public void initChannel(SocketChannel ch) throws Exception {
		//ch.pipeline().addFirst(bytesMetricsHandler);
		ch.pipeline().addLast(new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE));
		ch.pipeline().addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH));
		ch.pipeline().addLast(new ChunkedWriteHandler());
		ch.pipeline().addLast(objectFactory.getObject());
	}

}
